package com.terry.gamesimulator.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;

@RefreshScope
@Controller
public class IndexController {
    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){

        try{
            File jsonFile = ResourceUtils.getFile("classpath:static/game_list.json");
            String json = FileUtils.readFileToString(jsonFile);
            JSONArray jsonArray = JSON.parseArray(json);
            model.addAttribute("gameInfo",jsonArray.get(0));
            System.out.println(jsonArray);
        }catch (Exception e){

        }
        return "index";
    }

    @GetMapping({"/game/{gameid}"})
    public String indexPage2(Model model, @PathVariable("gameid")String gameid){

        try{
            File jsonFile = ResourceUtils.getFile("classpath:static/game_list.json");
            String json = FileUtils.readFileToString(jsonFile);
            JSONArray jsonArray = JSON.parseArray(json);
            model.addAttribute("gameInfo",jsonArray.get(Integer.parseInt(gameid)));
            System.out.println(jsonArray.get(Integer.parseInt(gameid)));
        }catch (Exception e){

        }
        return "index";
    }

    @Value("${user.testName}")
    private String testName;

    @GetMapping("/test")
    @ResponseBody
    public String test(){
        System.out.println(testName);
        return testName;
    }
}
